# -*- coding: utf-8 -*-
#
# Copyright 2008 Yejun Yang
#

import os, posixpath, stat

import mako.template

def compile_templates(root, input_encoding='utf-8', output=None):
    if output is None:
        output = root
    root = posixpath.normpath(root)
    root_len = len(root)
    output = posixpath.normpath(output)
    for dirpath, dirnames, filenames in os.walk(root):
        dirpath = posixpath.normpath(dirpath)
        if posixpath.basename(dirpath).startswith('.'): continue
        filenames = [f for f in filenames if not f.startswith('.') and not f.endswith('~') and not f.endswith('.py') and not f.endswith('.pyc')]
        outdir = posixpath.join(output , dirpath[root_len:])
        if not posixpath.exists(outdir):
            os.makedirs(outdir)
        if not posixpath.exists(posixpath.join(outdir, '__init__.py')):
            out = open(posixpath.join(outdir, '__init__.py'), 'w')
            out.close()
        for f in filenames:
            path = posixpath.join(dirpath, f).replace('\\','/')
            outfile = posixpath.join(outdir, f.replace('.','_')+'.py')
            filemtime = os.stat(path)[stat.ST_MTIME]
            if not os.path.exists(outfile) or os.stat(outfile)[stat.ST_MTIME] < filemtime:
                t = mako.template.Template(text=file(path).read(), filename=path, uri=path[root_len+1:], input_encoding=input_encoding)
                out = open(outfile, 'w')
                out.write( t.code)
                out.close()
            
            
if __name__ == "__main__":
    import sys
    if len(sys.argv)>1:
        compile_templates(*tuple(sys.argv[1:]))
    else:
        print "Usage: compile_template.py input_dir [input_encoding] [output_dir]"
    
    